package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.databinding.ActivityPatientListBinding
import com.compass.doctor.dialog.AppendDiagnoseDialog
import com.compass.doctor.ui.patient.adapter.PatientAdapter
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.doctor.base.BaseVBActivity
import com.compass.framework.ext.divider
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.visible
import com.compass.framework.utils.LogUtil
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * Description： 患者列表
 * Date:2023/12/22 22:28
 */
class PatientListActivity : BaseVBActivity<ActivityPatientListBinding>(), OnRefreshListener,
    OnLoadMoreListener {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, PatientListActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val patientViewModel: PatientViewModel by viewModels()
    private var mPage = 1
    private var key: String = ""
    private lateinit var mAdapter: PatientAdapter

    override fun initView(savedInstanceState: Bundle?) {
        initRecyclerView()
        mBinding.tvTitleBar.getRightLayout().onClick {
            AppendDiagnoseDialog.Builder(this).show()
        }

        mBinding.edtDiagnosis.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftInput()
                key = mBinding.edtDiagnosis.text.toString().trim()
                mPage = 1
                getPatientList()
            }
            false
        }

        mBinding.edtDiagnosis.addTextChangedListener {
            if (it.toString().isEmpty()) {
                key = mBinding.edtDiagnosis.text.toString().trim()
                mPage = 1
                getPatientList()
            }
        }
//        mBinding.edtDiagnosis.textChangeFlow()
//            .distinctUntilChanged()
//            .debounce(500)
//            .flowOn(Dispatchers.IO)
//            .onEach {
//                //这里走查询接口
//                key = mBinding.edtDiagnosis.text.toString()
//                getPatientList()
//            }
//            .launchIn(lifecycleScope)

    }

    override fun initData() {
        showLoading()
        getPatientList()
        patientViewModel.patientListLiveData.observe(this){
            dismissLoading()
            if (mPage == 1) {
                mAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
                } else {
                    mBinding.emptyView.gone()
                }
            } else {
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }
        }
    }

    /**
     * 获取推荐列表数据
     */
    private fun getPatientList() {
        patientViewModel.getPatientList(1, key = key)
    }


    private fun initRecyclerView() {
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@PatientListActivity)
            setOnLoadMoreListener(this@PatientListActivity)
        }
        mAdapter = PatientAdapter(1)
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
        mAdapter.onItemClickListener = { _: View, position: Int ->
            val patient = mAdapter.getItem(position)
            patient?.let {
                intent.putExtra("patient",patient)
                setResult(RESULT_OK, intent)
                finish()

            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getPatientList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getPatientList()
    }
}